<template>
    <div>
      <div class="search-bar">
        <span style="margin-right: 10px; width: 60px;">名称：</span>
        <el-input v-model="searchName" style="width: 150px;"  v-enter="keyHandleSearch"></el-input>
        <span style="margin-left: 20px; margin-right: 10px; width: 100px;">记录时间：</span>
        <el-date-picker
            v-model="startDate"
            type="date"
            placeholder="开始日期"
            style="width: 150px;"
            v-enter="keyHandleSearch"
        ></el-date-picker>
        <span style="margin-left: 10px; margin-right: 10px;">至</span>
        <el-date-picker
            v-model="endDate"
            type="date"
            placeholder="结束日期"
            style="width: 150px;"
            v-enter="keyHandleSearch"
        ></el-date-picker>
        <el-button type="primary" @click="handleSearch" style="margin-left: 20px;">
            <i class="el-icon-search"></i>搜索
        </el-button>
        <el-button type="primary" @click="resetting" style="margin-left: 10px;">
            <i class="el-icon-refresh"></i>重置
        </el-button>
        <el-button type="success" @click="showDialog" style="margin-left: 10px;">
            <i class="el-icon-plus"></i>添加
        </el-button>
        <add-wages :visible.sync="dialogVisible" @refreshList="handleRefreshList"/>
        <el-button type="warning" @click="handleExport" style="margin-left: 420px;">
            <i class="el-icon-download"></i>导出
        </el-button>
        <el-button type="warning" @click="handleTemplateDownload" style="margin-left: 10px;">
            <i class="el-icon-download"></i>模板下载
        </el-button>
        <input type="file" ref="fileInput" style="display: none;" @change="handleImport">
        <el-button type="warning" @click="openFileInput" style="margin-left: 10px;">
            <i class="el-icon-upload2"></i>导入
        </el-button>
      </div>
      <div class="table-from">
        <el-table :data="filteredData" style="width: 100%;height: 100%;" :fit="true">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column type="index" label="序号" width="60"></el-table-column>
            <el-table-column prop="name" label="名称" width="80" />
            <el-table-column prop="recordDate" label="记录时间" width="200" />
            <el-table-column prop="allWages" label="总工资" width="120" />
            <el-table-column prop="shouldWages" label="应发工资" width="120" />
            <el-table-column prop="actualWages" label="实发工资" width="120" />
            <el-table-column prop="coefficient" label="工资系数" width="150" />
            <el-table-column prop="basicWages" label="基本工资" width="150" />
            <el-table-column prop="performanceWages" label="绩效工资" width="150" />
            <el-table-column prop="socialSecurity" label="社保" width="150" />
            <el-table-column prop="accumulationFund" label="公积金" width="100" />
            <el-table-column fixed="right" label="操作" width="300" align="center">
            <template #default="{ row }">
                <el-button size="mini" type="primary" @click="handleEdit(row)">修改</el-button>
                <el-button size="mini" type="danger" @click="handleDeleteConfirm(row)">删除</el-button>
                <el-button size="mini" type="success" @click="handleDetail(row)">详情</el-button>
            </template>
            </el-table-column>
        </el-table>
      </div>
      <div style="text-align: right; padding-right: 20px;">
        <el-pagination background layout="prev, pager, next" :total="totalItems" @current-change="handleCurrentChange" />
      </div>
      <!--详情组件-->
      <wages-detail
        :visible.sync="detailVisible"
        :detail-data="selectedDetailData"
        @close="detailVisible = false"
      ></wages-detail>
      <!--修改组件-->
      <update-wages
        :visible.sync="updateVisible"
        :detail-data="updateDetailData"
        @close="updateVisible = false"
        @refreshList="handleRefreshList"
      ></update-wages>
    </div>
    
  </template>
  
  <script>
  import { handleErrorResponse } from '../error/errorHandler.js';
  import fileDownload from 'js-file-download'
  import AddWages from './AddWages.vue';
  import WagesDetail from './WagesDetail.vue';
  import UpdateWages from './UpdateWages.vue';
  export default {
    data() {
      return {
        tableData: [],
        searchName: '',
        startDate: '',
        endDate: '',
        currentPage: 1,
        pageSize: 10,
        totalItems: 0,
        dialogVisible: false,
        detailVisible: false,
        selectedDetailData: {},
        updateVisible: false,
        updateDetailData: {}
      };
    },
    computed: {
      filteredData() {
        return this.tableData
      }
    },
    components: {
      AddWages,
      WagesDetail,
      UpdateWages
    },
    directives: {
      enter: {
        inserted: function (el, binding) {
          el.addEventListener('keyup', function (event) {
            if (event.keyCode === 13) { // 如果按下的是回车键
              binding.value(); // 调用传入的回调函数
            }
          });
        }
      }
   },
    methods: {

      //搜索
      keyHandleSearch(){
        this.currentPage = 1;
        this.handleSearch();
      },
      async handleSearch() {
        try {
            // 格式化日期
            const formattedStartDate = this.startDate ? this.formatDate(new Date(this.startDate)) : '';
            const formattedEndDate = this.endDate ? this.formatDate(new Date(this.endDate)) : '';

            let params = {
            pageSize: this.pageSize,
            pageNum: this.currentPage,
            name: this.searchName,
            recordDateStart: formattedStartDate,
            recordDateEnd: formattedEndDate
            };
            const response = await this.$axios.get("/wages/pageList", { params,
                headers: {
                'satoken': localStorage.getItem('satoken')
            }   
            });
            console.log("Response:", response);
            if(response.data.success){
                console.log("esponse.data.data:", response.data.data.records);
                this.tableData = response.data.data.records; // 更新数据列表
                this.totalItems = response.data.data.total; // 更新总条目数
            }else{
                handleErrorResponse(response.data.msg,this.$router,this.$message);
                
            } 
        } catch (error) {
            console.error('Error fetching data:', error);
        }
      },


    //格式化日期
    formatDate(date) {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
     },


    //修改
    async handleEdit(row) {
      console.log('Edit:', row);
      try{
        const response = await this.$axios.get(`/wages/getWagesById/${row.id}`, {
        headers: {
          'satoken': localStorage.getItem('satoken')
        }
        });
        if (response.data.success) {
          // 更新选中的详情数据
          this.updateDetailData = response.data.data;
          // 显示详情组件
          this.updateVisible = true;
        } else {
          // 处理失败情况
          this.$message.error(response.data.msg || '获取详情失败');
        }
        console.log('response:', response);
      }catch(error){
        console.error('Error fetching data:', error);
      }
    },

    // 点击删除按钮时触发
    handleDeleteConfirm(row) {
      // 弹出确认框
      this.$confirm('此操作将永久删除该数据，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击了确定按钮
        this.handleDelete(row);
      }).catch(() => {
        // 用户点击了取消按钮或点击了遮罩层
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    //删除
    async handleDelete(row) {
    console.log('Delete:', row);
      try{
        const response = await this.$axios.delete(`/wages/deleteById/${row.id}`, {
        headers: {
          'satoken': localStorage.getItem('satoken')
        }
        
        });
        if(response.data.success){
          this.$message({
					message:'删除成功',
					type: 'success'
				  });
          this.handleSearch();
        }else{
          this.$message.error(response.data.msg);
        }
      }catch(error){
        console.error('Error fetching data:', error);
      }
    },


    //详情
    async handleDetail(row) {
      console.log('Detail:', row);
      try{
        const response = await this.$axios.get(`/wages/getWagesById/${row.id}`, {
        headers: {
          'satoken': localStorage.getItem('satoken')
        }
        });
        if (response.data.success) {
          // 更新选中的详情数据
          this.selectedDetailData = response.data.data;
          // 显示详情组件
          this.detailVisible = true;
        } else {
          // 处理失败情况
          this.$message.error(response.data.msg || '获取详情失败');
        }
        console.log('response:', response);
      }catch(error){
        console.error('Error fetching data:', error);
      }
    },

    // 关闭详情组件时重置可见状态
    handleDetailClose() {
      this.detailVisible = false;
    },

    //列表导出
    async handleExport() {
        try{
            // 格式化日期
            const formattedStartDate = this.startDate ? this.formatDate(new Date(this.startDate)) : '';
            const formattedEndDate = this.endDate ? this.formatDate(new Date(this.endDate)) : '';
            let params = {
            name: this.searchName,
            recordDateStart: formattedStartDate,
            recordDateEnd: formattedEndDate
            };
            const response = await this.$axios.get('/wages/excelExport', {params,
            responseType: 'blob', // 声明响应类型为 blob
            headers: {
                'satoken': localStorage.getItem('satoken')
            }
            });
            fileDownload(response.data,"工资列表.xlsx")
            }catch(error){
                console.error('Error fetching data:', error);
                this.$message.error(error);
            }
    },

    showDialog() {
      this.dialogVisible = true;
    },
    //excel模板下载
    async handleTemplateDownload() {
        try{
          const response = await this.$axios.get('/wages/excelDownload', {
          responseType: 'blob', // 声明响应类型为 blob
          headers: {
            'satoken': localStorage.getItem('satoken')
          }
        });
            fileDownload(response.data,"工资列表导入模板.xlsx")
        }catch(error){
            console.error('Error fetching data:', error);
            this.$message.error(error);
        }
    },


      //导入
    openFileInput() {
        this.$refs.fileInput.click(); // 打开文件选择对话框
    },


    //导入
    async handleImport() {
        try{
            const file = event.target.files[0];
            const formData = new FormData();
            formData.append('file', file);
            // 发送 POST 请求到后端接口
            const response = this.$axios.post('/wages/excelImport', formData, {
                headers: {
                'Content-Type': 'multipart/form-data',
                'satoken': localStorage.getItem('satoken')
                }
        })
        this.handleSearch();
        this.$message({
					message:'导入成功',
					type: 'success'
				});
        }catch(error){
            console.error('Error fetching data:', error);
            this.$message.error(error);
        }
    },
    // 刷新列表方法
    handleRefreshList() {
      this.handleSearch(); // 这里调用父组件中的方法来刷新列表数据
    },
    //分页
    handleCurrentChange(page) {
        this.currentPage = page;
        this.handleSearch();
     },

    resetting() {
        // 清空搜索框中的内容
        this.searchName = '';
        this.startDate = '';
        this.endDate = '';
        // 调用搜索方法重新获取数据
        this.handleSearch();
    },
  },

  mounted() {
    this.handleSearch();
  }

  };
  </script>
  
  <style scoped>
  .search-bar {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
  }
  .search-bar span {
    margin-left: 10px;
  }
  .table-from {
  height: 600px; /* 设置表格高度 */
  overflow-y: auto; /* 启用垂直滚动 */
}

  </style>
  